package com.mzkj.wanjulaile.mobile.api.modules.shoppingCart.controller;


import com.mzkj.common.data.StatusCode;
import com.mzkj.common.utils.Collections3;
import com.mzkj.common.utils.DateUtils;
import com.mzkj.common.utils.StringUtils;
import com.mzkj.wanjulaile.mobile.api.common.controller.BaseController;
import com.mzkj.wanjulaile.mobile.api.common.entity.ResultEntity;
import com.mzkj.wanjulaile.mobile.api.modules.account.entity.Account;
import com.mzkj.wanjulaile.mobile.api.modules.account.entity.VipCategory;
import com.mzkj.wanjulaile.mobile.api.modules.account.service.AccountService;
import com.mzkj.wanjulaile.mobile.api.modules.account.service.BuyVipService;
import com.mzkj.wanjulaile.mobile.api.modules.account.service.VipCategoryService;
import com.mzkj.wanjulaile.mobile.api.modules.appointment.entity.AppointmentCollection;
import com.mzkj.wanjulaile.mobile.api.modules.shoppingCart.entity.ShoppingCart;
import com.mzkj.wanjulaile.mobile.api.modules.shoppingCart.service.ShoppingCartService;
import com.mzkj.wanjulaile.mobile.api.modules.stock.entity.Stock;
import com.mzkj.wanjulaile.mobile.api.modules.stock.service.StockService;
import com.mzkj.wanjulaile.mobile.api.modules.toy.entity.Toy;
import com.mzkj.wanjulaile.mobile.api.modules.toy.service.ToyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by ianly on 16/10/18.
 */
@RequestMapping(value = "auth/shoppingCart")
@Controller
public class ShoppingCartAuthController extends BaseController {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private AccountService accountService;

    @Autowired
    private ToyService toyService;
    @Autowired
    private StockService stockService;
    @Autowired
    private VipCategoryService vipCategoryService;

    /**
     * 添加购物车
     *
     * @param id 玩具id
     * @return
     */
    @RequestMapping(value = "addShoppingCart")
    @ResponseBody
    public ResultEntity<String> addShoppingCart(String id, HttpServletRequest request) {
        ResultEntity<String> result = new ResultEntity<String>();
        String accountId = (String) request.getAttribute("accountId");
        try {
            Stock stock = stockService.getByToyId(id);
//            Account account = accountService.findAccountByOpenid(openID);
            Account account = accountService.get2(accountId);
            Toy toy = toyService.get(id);
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setAccount(account);
            shoppingCart.setToy(toy);
            List<ShoppingCart> Cart = shoppingCartService.getByAcIdToyId(shoppingCart);
            //库存不足
            if (stock.getRealCount() == 0) {
                result.setStatusCode(StatusCode.SC4003.getValue());
                result.setMsg(StatusCode.SC4003.getDesc());
            } //是否重复加入购物车
            else if (Cart != null && !Collections3.isEmpty(Cart)) {
                result.setStatusCode(StatusCode.SC4004.getValue());
                result.setMsg(StatusCode.SC4004.getDesc());
            } else {
                ShoppingCart shopCart = new ShoppingCart();
                shopCart.setAccount(account);
                shopCart.setToy(toy);
                shopCart.setToyCount(1);
                shopCart.setIsNewRecord(true);
                shoppingCartService.save(shopCart);
                result.setStatusCode(StatusCode.SC0.getValue());
                result.setMsg(StatusCode.SC0.getDesc());
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatusCode(StatusCode.SC5000.getValue());
            result.setMsg(StatusCode.SC5000.getDesc());
        }
        return result;
    }

    @ResponseBody
    @RequestMapping("/addCartAfterAppoint")
    public ResultEntity<String> addCartAfterAppoint(String id, HttpServletRequest request) {
        ShoppingCart cart = new ShoppingCart();
        ResultEntity<String> result = new ResultEntity<String>();
        String accountId = (String) request.getAttribute("accountId");
        cart.setAccount(new Account(accountId));
        cart.setToy(new Toy(id));
        try {
            if (Collections3.isEmpty(shoppingCartService.getByAcIdToyId(cart))) {
                cart.setAccount(new Account(accountId));
                cart.setToy(new Toy(id));
                cart.setToyCount(1);
                shoppingCartService.save(cart);
                result.setStatusCode(StatusCode.SC0.getValue());
                result.setMsg(StatusCode.SC0.getDesc());
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatusCode(StatusCode.SC5000.getValue());
            result.setMsg(StatusCode.SC5000.getDesc());
        }
        return result;
    }


    /**
     * 获取购物车列表
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/getCartList")
    public ResultEntity<List<ShoppingCart>> getCartList(HttpServletRequest request) {
        String accountId = (String) request.getAttribute("accountId");
        ResultEntity<List<ShoppingCart>> result = new ResultEntity<List<ShoppingCart>>();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setAccount(new Account(accountId));
        try {
            List<ShoppingCart> carts = shoppingCartService.findList(shoppingCart);
            result.setData(carts);
            result.setStatusCode(StatusCode.SC0.getValue());
            result.setMsg(StatusCode.SC0.getDesc());
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatusCode(StatusCode.SC4002.getValue());
            result.setMsg(StatusCode.SC4002.getDesc());
        }
        return result;
    }

    /**
     * 购物车结算
     *
     * @param ids     购物车数据id数组
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/cartSettle")
    public ResultEntity<Account> cartSettle(String[] ids, HttpServletRequest request) {
        ResultEntity<Account> result = new ResultEntity<Account>();
        String accountId = (String) request.getAttribute("accountId");
        if (ids == null || ids.length <= 0) {
            return new ResultEntity<>(StatusCode.SC4001);
        }
        try {
            Account account = accountService.get2(accountId);
            VipCategory vipCategory = vipCategoryService.getByType(account.getVipType());
            if (account.getVipType().equals(0)) {
                result.setStatusCode(StatusCode.SC4006.getValue());
                result.setMsg("成为会员即可下单，宝宝明天就能玩上我们的玩具啦！");
                return result;
            }
            if (StringUtils.isNotEmpty(account.getVipStart()) && DateUtils.compareDate(DateUtils.parseDate(account.getVipEnd()), new Date()) <= 0) {
                result.setStatusCode(StatusCode.SC4005.getValue());
                result.setMsg(StatusCode.SC4005.getDesc());
                return result;
            }//判断购买产品与账号对应vip权限是否相符
            List<ShoppingCart> shoppingCarts = shoppingCartService.findListByIds(Arrays.asList(ids));
            //租赁玩具总星值
            int rentToyStars = 0;
            for (ShoppingCart cart : shoppingCarts) {
                if (cart.getToy().getOnShelf().equals("0")) {
                    result.setStatusCode(StatusCode.SC40010.getValue());
                    result.setMsg("玩具" + cart.getToy().getName() + "已下架,请重新选择");
                    return result;
                }
                rentToyStars += cart.getToy().getStar();
            }
            if (vipCategory.getStar() < rentToyStars) {
                //所选玩具星值已高于当前会员套餐 提示
                if (vipCategory.getStar() <2) {
                    result.setStatusCode(StatusCode.SC40011.getValue());
                } else {
                    result.setStatusCode(StatusCode.SC4001101.getValue());
                }
                result.setMsg(StatusCode.SC40011.getDesc());
                return result;
            }
            if (vipCategory.getStar() > rentToyStars) {
                result.setStatusCode(StatusCode.SC40012.getValue());
                result.setMsg("您还可以再选一个玩具,不选了么?");
                return result;
            }
            result.setStatusCode(StatusCode.SC0.getValue());
            result.setMsg(StatusCode.SC0.getDesc());
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatusCode(StatusCode.SC5000.getValue());
            result.setMsg("结算失败");
        }
        return result;
    }

    /**
     * 根据id删除购物车
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("/delete")
    public ResultEntity<String> deleteCart(String id) {
        ResultEntity<String> result = new ResultEntity<>();
        ShoppingCart cart = new ShoppingCart(id);
        try {
            //如果是预约玩具 删除预约表中的玩具
            ShoppingCart temp = shoppingCartService.get(cart);
            AppointmentCollection app = new AppointmentCollection();
            app.setAccount(temp.getAccount());
            app.setToy(temp.getToy());
            app.setType("1");
//            appointmentCollectionService.deleteByAccountIdAndToy(app);
//            shoppingCartService.delete(cart);
            shoppingCartService.delBoth(cart, app);
            result.setStatusCode(StatusCode.SC0.getValue());
            result.setMsg(StatusCode.SC0.getDesc());
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatusCode(StatusCode.SC5000.getValue());
            result.setMsg(StatusCode.SC5000.getDesc());
        }
        return result;
    }

    /**
     * 批量删除购物车
     *
     * @param ids 购物车 id 数组
     * @return
     */
    @ResponseBody
    @RequestMapping("/batchDelete")
    public ResultEntity<String> deleteCart(String[] ids) {
        ResultEntity<String> result = new ResultEntity<>();
        try {
            if (ids == null || ids.length <= 0) {
                return new ResultEntity<>(StatusCode.SC4001);
            }
            shoppingCartService.batchDeleteByIds(Arrays.asList(ids));
            result.setStatusCode(StatusCode.SC0.getValue());
            result.setMsg(StatusCode.SC0.getDesc());
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatusCode(StatusCode.SC5000.getValue());
            result.setMsg(StatusCode.SC5000.getDesc());
        }
        return result;
    }

//    @ResponseBody
//    @RequestMapping("/addShoppingCart")
//    public ResultEntity<String> addShoppingCart(String accountId,String toyId){
//        ShoppingCart cart = new ShoppingCart();
//        ResultEntity<String> result = new ResultEntity<String>();
//        cart.setAccount(new Account(accountId));
//        cart.setToy(new Toy(toyId));
//        try {
//            if (Collections3.isEmpty(shoppingCartService.getByAcIdToyId(cart))){
//                cart.setAccount(new Account(accountId));
//                cart.setToy(new Toy(toyId));
//                cart.setToyCount(1);
//                shoppingCartService.save2(cart);
//                result.setStatusCode(WXConstant.STATUS_CODE_SUCCESS);
//                result.setMsg("");
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            result.setStatusCode(WXConstant.STATUS_CODE_FAILED);
//            result.setMsg("添加购物车失败");
//        }
//        return result;
//    }

    /**
     * 获取购物车数量
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/shoppingCartCount")
    public ResultEntity<Integer> shoppingCartCount(HttpServletRequest request) {
        ResultEntity<Integer> result = new ResultEntity<Integer>();
        String accountId = (String) request.getAttribute("accountId");
        try {
            List<ShoppingCart> carts = shoppingCartService.findList2ByAccountId(accountId);
            result.setStatusCode(StatusCode.SC0.getValue());
            result.setMsg(StatusCode.SC0.getDesc());
            result.setData(Collections3.isEmpty(carts) ? 0 : carts.size());
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatusCode(StatusCode.SC4002.getValue());
            result.setMsg(StatusCode.SC4002.getDesc());
        }
        return result;
    }

    /**
     * 删除预约时 删除购物车中的预约玩具
     *
     * @param toyId   玩具id
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/deleteByToyAndAcc")
    public ResultEntity<String> deleteByToyAndAcc(String toyId, HttpServletRequest request) {
        ResultEntity<String> result = new ResultEntity<>();
        String accountId = (String) request.getAttribute("accountId");
        try {
            List<String> toyIds = new ArrayList<String>();
            toyIds.add(toyId);
            shoppingCartService.batchDelete(toyIds, accountId);
            result.setStatusCode(StatusCode.SC0.getValue());
            result.setMsg(StatusCode.SC0.getDesc());
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatusCode(StatusCode.SC5000.getValue());
            result.setMsg(StatusCode.SC5000.getDesc());
        }
        return result;
    }

}
